import time

from playwright import sync_api
from playwright.sync_api import BrowserContext

from models.config import Config
from models.container import Container
from utils.paths import CONFIG_PATH
from utils.utils import load_yaml, request_json


class Hubstudio:
    @classmethod
    def get_container(cls) -> list[Container]:
        page = 0
        page_size = 200
        envs = []

        while True:
            page += 1

            response = request_json(
                url=Config.hubstudio.baseUrl + Config.hubstudio.paths.envList,
                payload={
                    'current': page,
                    'size': page_size,
                }
            )

            if len(response['data']['list']) == 0:
                break

            for env in response['data']['list']:
                if "买家号" not in env['containerName']:
                    continue
                envs.append(Container(
                    code=env['containerCode'],
                    name=env['containerName'],
                    proxyHost=env['proxyHost'],
                    proxyPort=env['proxyPort']
                ))

            time.sleep(1)

        return envs

    def start_container(self, container_code: int) -> str:
        payload = {
            'containerCode': container_code
        }

        response = request_json(
            url=Config.hubstudio.baseUrl + Config.hubstudio.paths.envStart,
            payload=payload
        )

        return response['data']['debuggingPort']

    @classmethod
    def connect_browser(cls, port: str) -> BrowserContext:
        pwr = sync_api.sync_playwright().start()
        browser = pwr.chromium.connect_over_cdp("http://127.0.0.1:" + str(port))
        context = browser.contexts[0]
        return context


